package com.xmx.ordercenter.listener;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.xmx.ordercenter.entity.OrderEntity;
import com.xmx.ordercenter.service.OrderService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import java.io.IOException;
import java.util.Map;

import static com.xmx.common.rabbitDto.OrderDto.*;

@Component
@RabbitListener(queues = {ORDER_CLOSE_QUEUE})
@Slf4j
public class OrderMsgListener {
    @Resource
    private OrderService orderService;

    @SneakyThrows
    @RabbitHandler
    public void closeOrder(Map map, Message messag , Channel channel){
        log.error("进入-====================》》closeOrder");
        Integer orderId = (Integer) map.get("orderId");
        String orderSn = (String) map.get("orderSn") ;
        log.info("=============收到过期订单消息，开始关闭订单========{}",orderSn);
        try {

            /**
             * 查询订单是否存在，是否关闭
             */
            UpdateWrapper<OrderEntity> updateWrapper = new UpdateWrapper<>();
            updateWrapper.lambda().eq(OrderEntity::getId, orderId).set(OrderEntity::getOrderStatus, 103);
            boolean result = orderService.update(updateWrapper);
            if(result){
                log.info("====================订单关闭成功！！");
            }else {
                log.error("===================订单关闭失败！！，订单不存在，订单号为{}",orderId);
            }
            //尝试消费消息
            channel.basicAck(messag.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            log.info("======关闭订单异常，关闭订单消息回退到消息队列======");
            channel.basicReject(messag.getMessageProperties().getDeliveryTag(),true);
            e.printStackTrace();
        }


    }
}
